package com.sanmubird.mywebframework.embeddeddatabase.config;

import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.boot.logging.LogLevel;
import org.springframework.boot.logging.Slf4JLoggingSystem;
import org.springframework.boot.logging.logback.LogbackLoggingSystem;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.ClassPathResource;
import org.springframework.jdbc.datasource.init.ScriptUtils;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * @author sam
 */
@Slf4j
@Configuration
public class ClientConfiguration {
    public ClientConfiguration() {
    }

    @Primary
    @Bean
    @DependsOn({"mariaDB4j"})
    public DataSource dataSource(MariaDataSourceProperties mariaDataSourceProperties) throws SQLException {
        // 执行 初始化数据库 所需要的脚本
        HikariConfig hikariConfig = new HikariConfig();
        hikariConfig.setDriverClassName(mariaDataSourceProperties.getDriverClassName());
        hikariConfig.setJdbcUrl(mariaDataSourceProperties.getUrl());
        hikariConfig.setUsername(mariaDataSourceProperties.getUsername());
        hikariConfig.setPassword(mariaDataSourceProperties.getPassword());
        HikariDataSource dataSource = new HikariDataSource(hikariConfig);
        String schemaPath = mariaDataSourceProperties.getSchema().get(0);
        if (StringUtils.isNotBlank(schemaPath)) {
            ClassLoader classLoader = ServeConfiguration.class.getClassLoader();
            Slf4JLoggingSystem log4J2LoggingSystem = new LogbackLoggingSystem(classLoader);
            log4J2LoggingSystem.setLogLevel("org.springframework.jdbc.datasource.init", LogLevel.DEBUG);
            Connection connection = dataSource.getConnection();
            ScriptUtils.executeSqlScript(connection, new ClassPathResource(schemaPath));
            String dataSqlPath = mariaDataSourceProperties.getData().get(0);
            if (StringUtils.isNotBlank(dataSqlPath)) {
                ScriptUtils.executeSqlScript(connection, new ClassPathResource(dataSqlPath));
            }
        }
        return dataSource;
    }


}
